import {messages, uniqueObjArr, formatNumber} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, Input, Popconfirm, Select, Popover, Switch, Button, message, InputNumber } from 'antd';
import 'styles/components/template/add-table-cell.scss'
import ResizeTable from 'components/resize-table'
import Chooser from 'components/chooser';
import config from "config";
import FileUpload from 'components/file-upload'
import SlideFrame from 'components/slide-frame';

const { Option } = Select

class EditableCell extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: this.props.value,
      originValue: this.props.value,
      column: this.props.column,
      formTypeData: [],
      record: this.props.record,
      user: this.props.user
    }
  }

  showDraw(value){
    this.props.clickFun(value)
  }

  // 礼品类型的联动
  onChange = (value) => {
    let { column, user } = this.props
    if (column.dataIndex === 'type') {
      let applyQuantity = Number(this.props.form.getFieldValue('applyQuantity'))
      let unitPrice = Number(value.split(',')[1])
      this.props.form.setFieldsValue({
        unitPrice,
        amount: applyQuantity ? applyQuantity * unitPrice : ''
      })
    }else if (column.dataIndex === 'sendWayText') {
      let data = value.split(',')
      if (data[0] === '自取') {
        this.props.isRequiredFun(false, 'deliveryInfo')
        this.props.form.setFieldsValue({
          link: user.fullName,
          phone: user.mobile
        })
      } else {
        this.props.isRequiredFun(true, 'deliveryInfo')
        this.props.form.setFieldsValue({
          link: '',
          phone: ''
        })
      }
    }
  }

  // 接收人信息12个月内是否超过2次
  switchChange = (value) => {
    this.props.isRequiredFun(value, 'remark')
  }

  // 申请数量的联动
  onInput = (value) => {
    let { column, record } = this.props
    console.log(column.dataIndex, value, column, record)
    if (column.dataIndex === 'applyQuantity') {
      let receiveQuantity = Number(value)
      let unitPrice = Number(this.props.form.getFieldValue('unitPrice'))
      this.props.form.setFieldsValue({
        receiveQuantity,
        amount: receiveQuantity && unitPrice ? receiveQuantity * unitPrice : ''
      })
    } else if (column.dataIndex === 'receiveQuantity') {
      let unitPrice = Number(record.unitPrice)
      let amount = value * unitPrice
      this.props.form.setFieldsValue({
        amount
      })
    } else if (column.dataIndex === 'quantity') {
      if (this.props.form.getFieldValue('giftType')) {
        let quantity = Number(value)
        let unitPrice = Number((this.props.form.getFieldValue('giftType') || '').split(',')[1]) || record.unitPrice
        this.props.form.setFieldsValue({
          amount: quantity && unitPrice ? quantity * unitPrice : ''
        })
      }
    }
  }

  // 判断当前编辑行是输入框还是选择框等
  getInput = (value) => {
    const inputType = this.props.column.inputType
    const dataIndex = this.props.column.dataIndex
    const formTypeData = this.props.column.value || []
    const attachmentImages = value || []
    if (inputType === 'select' && (dataIndex === 'type' || dataIndex === 'sendWayText' || dataIndex === 'address' || dataIndex === "gift" || dataIndex === "giftType")) {
      return <Select onChange={this.onChange}>
          {
            formTypeData.map((item) => {
              return (
                <Option value={`${item.messageKey},${item.remark},${item.code}`}>{item.messageKey}</Option>
              )
            })
          }
          </Select>
    } else if (inputType === 'chooser' && dataIndex === 'employeeName') {
      return  <Chooser
                single
                placeholder={messages('common.please.select')}
                labelKey="fullName"
                valueKey="employeeID"
                type="user"
            />
    } else if (inputType === 'chooser' && dataIndex === 'governmentName') {
      return  <Chooser
                placeholder={messages('common.please.select')}
                selectorItem={{
                  key: "code",
                  title: "选择",
                  columns: [
                    // {
                    //   title: "编码",
                    //   dataIndex: "code",
                    // },
                    { title: "名称", dataIndex: "messageKey" },
                  ],
                  searchForm: [],
                  url: `${config.baseUrl}/api/public/assembly/custom/enumerations/${formTypeData}`,
                }}
                single
                valueKey="code"
                labelKey="messageKey"
              />
    } else if (inputType === 'switch') {
      return <Switch defaultChecked={value} onChange={this.switchChange} className="switchWidth"/>
    } else if (inputType === 'upload') {
      return <FileUpload
                  showMaxNum={false}
                  fileSize={10}
                  defaultFileList={attachmentImages}
                  attachmentType="INVOICE_IMAGES"/>
    } else if (inputType === 'inputNumber' && (dataIndex === 'applyQuantity' || dataIndex === 'receiveQuantity' || dataIndex === 'quantity')) {
      return <InputNumber
                onChange={this.onInput}
                formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                parser={value => value.replace(/,/g, '')}
                min={0}/>
    } else if (inputType === 'inputNumber' && dataIndex === 'amount') {
      return <InputNumber
              formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
              parser={value => value.replace(/\$\s?|(,*)/g, '')}
              min={0}/>
    }
    return <Input/>;
  }

  render() {
    const { value } = this.state;
    const { editable, column, operationKey } = this.props
    const { getFieldDecorator } = this.props.form
    let newValue = column.dataIndex === 'isTwice' ? (value === '是' ? true : false) : value
    console.log("operationKey", operationKey)
    return (
      <div className="editable-cell">
        {editable && column.editable ? (
          <div className="editable-cell-input-wrapper">
            <div style={{paddingTop: column.dataIndex === 'appendix' ? '10px' : '0'}}>
              {
                column.isReadOnly && (
                  <Form.Item
                    style={{
                      margin: 0,
                    }}
                  >
                    {getFieldDecorator(column.dataIndex, {
                        initialValue: value,
                        rules: [
                            { required: column.isRequired, message: operationKey !== 'receiver' ? ' ' : `请输入${column.trueTitle ? column.trueTitle : column.title}!` },
                        ],
                    })(
                      column.inputType === 'inputNumber' ? <InputNumber
                        disabled
                        formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                        parser={value => value.replace(/\$\s?|(,*)/g, '')}
                      /> : <Input
                        disabled
                      />
                    )}
                  </Form.Item>
                )
              }
              {
                !column.isReadOnly && (
                  <Form.Item
                    style={{
                      margin: 0,
                    }}
                  >
                    {getFieldDecorator(column.dataIndex, {
                        initialValue: newValue,
                        rules: [
                            { required: column.isRequired, message: operationKey !== 'receiver' ? ' ' : `请输入${column.trueTitle ? column.trueTitle : column.title}!` },
                        ],
                    })(
                      this.getInput(newValue)
                    )}
                  </Form.Item>
                )
              }

            </div>
          </div>
        ) : (
          <div className="editable-cell-text-wrapper">
            {
              column.dataIndex === 'appendix' ?
                (value && value.length > 0 ? (<a onClick={() => this.showDraw(value)}>查看</a>) :'-') :
                (value ?
                  column.inputType === 'inputNumber' ?
                  column.dataIndex === 'amount' ? <Popover placement="topLeft" content={formatNumber(Number(value).toFixed(2))}>{formatNumber(Number(value).toFixed(2))}</Popover> : <Popover placement="topLeft" content={formatNumber(value)}>{formatNumber(value)}</Popover> :
                    <Popover placement="topLeft" content={value}>{value}</Popover>
                  : '-')
            }
          </div>
        )}
      </div>
    )
  }
}

class AddTableCell extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      columns:[],
      editingKey: '',
      visible: false,
      slideFrameKey: 'slideFrameKey0',
      fileList: []
    }
  }

  componentWillReceiveProps (nextProps) {
    let { isEdit, isEditCancel, operationKey, columns, isCancleDeleteBtn } = nextProps
    columns.map(item => {
      item.render = (value, record) => {
        const editable = this.isEditing(record)
        return(<EditableCell value={value}
                    column={item}
                    editable={editable}
                    form={this.props.form}
                    clickFun={this.showDraw}
                    record={record}
                    user={this.props.loginUser}
                    operationKey={operationKey}
                    isRequiredFun={this.changeIsRequired}/>
      )}
      if (item.needFixed) {
        item.fixed = 'left';
      }
    });
    if (isEdit) {
      columns.push(
        {
          title: messages('setting.key1097'/*操作*/),
          dataIndex: 'operation',
          width: 100,
          fixed: 'right',
          key: operationKey,
          render: (text, record, index) => {
            const { editingKey } = this.state;
            const editable = this.isEditing(record);
            return editable ? (
              <span>
                <a
                  onClick={() => this.save(record, index)}
                  style={{ marginRight: 8 }}
                >
                  保存
                </a>
                <Popconfirm title="您真的要取消吗?" onConfirm={() => this.cancel(record.key)}>
                  <a>取消</a>
                </Popconfirm>
              </span>
            ) : (
              <span>
                {
                  !isEditCancel && (<a style={{ marginRight: 8 }} disabled={editingKey !== ''} onClick={() => this.edit(record.key, record)}>
                  编辑
                  </a>)
                }
                {
                  !isCancleDeleteBtn && (
                    <Popconfirm title="您真的要删除这条数据吗?" onConfirm={() => this.onDelete(record)}>
                        <a disabled={editingKey !== ''}>删除</a>
                    </Popconfirm>
                  )
                }
              </span>
            );
          },
        }
      )
    }
    this.setState({
      columns: uniqueObjArr(columns, 'dataIndex')
    })
  }

  componentDidMount() {
    this.props.onRef(this)
  }

  showDraw = (value) => {
    this.setState({
      fileList: value,
      visible: true
    })
  }

  changeIsRequired = (value, dataIndex) => {
    let {columns} = this.state
    let index = columns.findIndex(item => item.dataIndex === dataIndex)
    columns[index].editable = value
    this.setState({
      columns
    })
  }

  renderContent = () => {
    let { fileList } = this.state
    return (
      <div>
        {
          fileList.map(item => {
            return <a href={item.fileURL} target="_blank">{item.fileName}</a>
          })
        }
        <div className="slide-footer">
          <Button onClick={this.handleOnHideSlide}>确定</Button>
        </div>
      </div>
      )
  }

  /**
   * 关闭抽屉
   */
  handleOnHideSlide = () => {
    this.setState({
      visible: false
    })
  }

  /**
   *  判断当前是否需要有输入框编辑
  */
  isEditing = record => record.key === this.state.editingKey;

  /**
   * 取消
  */
  cancel = () => {
    this.setState({ editingKey: '' });
  };

 /**
   * 保存
   * record 当前保存按钮的表格的行数据
   * index 当前保存按钮的表格的行数
   * row 当前保存行的编辑的数据
  */
  save(record, index) {
    this.props.form.validateFields((error, row) => {
      // if (error && this.props.operationKey !== 'receiver') {
      //   message.info('请将输入框填写完整再保存！')
      //   return;
      // }
      this.onChange('onSave', {
        record,
        index,
        row,
        unitPrice: Number((this.props.form.getFieldValue('giftType')||'').split(',')[1]) || record.unitPrice
      })
    });
  }

  /**
   * 编辑
  */
  edit (key, record) {
    let {columns} = this.state
    let index = columns.findIndex(item => item.dataIndex === 'deliveryInfo')
    let indexType = columns.findIndex(item => item.dataIndex === 'type')
    if (indexType && columns[indexType] && !columns[indexType].editable && index && columns[index]) {
      if (record.sendWayText === '自取') {
        columns[index].editable = false
      } else {
        columns[index].editable = true
      }
    }
    let isTwiceIndex = columns.findIndex(item => item.dataIndex === 'isTwice')
    let isTwiceIndexType = columns.findIndex(item => item.dataIndex === 'remark')
    if (isTwiceIndexType && columns[isTwiceIndexType] && isTwiceIndex && columns[isTwiceIndex]) {
      if (record.isTwice === '是') {
        columns[isTwiceIndexType].editable = true
      } else {
        columns[isTwiceIndexType].editable = false
      }
    }
    this.setState({
        editingKey: key,
        columns
    }, () => {
      if (record.employeeName) {
        this.props.form.setFieldsValue({
          employeeName: [{fullName: record.employeeName, employeeID: record.employeeId}]
        })
      }
      if (record.governmentName) {
        this.props.form.setFieldsValue({
          governmentName: [{messageKey: record.governmentName, code: record.governmentCode}]
        })
      }
    })
  }

  /**
   * 删除
  */
  onDelete = (record) => {
    this.onChange('onDelete', record)
  };

  /**
   * 增加
  */
  handleAdd = (obj) => {
    const { editingKey } = this.state
    const { value } = this.props
    if (editingKey) {
      return
    }
    let key = new Date().getTime();
    let newData = {key: key};
    this.props.columns.map(item => {
      if (item.defaultValue) {
        newData[item.dataIndex] = item.defaultValue
      }
    });
    value.push(newData);
    this.onChange('onChange', value)
    this.setState({
      editingKey: key
    }, () => {
      if (obj) {
        this.props.form.setFieldsValue({
          employeeName: [{fullName: obj.fullName, employeeID: obj.employeeID}],
          address: obj.address ? obj.address : undefined,
          contactWay: obj.contactWay ? obj.contactWay : undefined
        })
      }
    })
  };

  /**
   * 编辑、保存触发父组件的统一方法
  */
  onChange = (Func, changedValue) => {
    if (this.props[Func]) {
      this.props[Func](changedValue)
    }
  };

  render() {
    const { columns, slideFrameKey, visible } = this.state;
    const { loading, title, value } = this.props
    return (
      <div>
        <Form>
          <ResizeTable rowKey="key"
                loading={loading}
                dataSource={value}
                columns={columns}
                pagination={false}
                scroll={{x:true}}
                title={title}
                bordered
                size="middle"/>
        </Form>

        <SlideFrame
          slideFrameKey={slideFrameKey}
          title={messages('request.key805')}
          width={'730px'}
          show={visible}
          content={this.renderContent}
          onClose={this.handleOnHideSlide}
        />
      </div>
    );
  }
}

/**
 *
 * @type columns，每项格式和table的columns一样，新增以下字段
 * {
      editable: false,         //可选，是否可编辑
      isRequired: false,      //可选，是否必填
      defaultValue: '',      //可选，默认值
      inputType： '', // 输入框的类型 input select
 * }
 */
AddTableCell.propTypes = {
  columns: React.PropTypes.array.isRequired,
  value: React.PropTypes.array, // 当前table的列表数据
  onChange: React.PropTypes.func,  //修改当前table列表数据
  onDelete: React.PropTypes.func,  //删除的回调
  onSave: React.PropTypes.func,  //保存后的回调
};

AddTableCell.defaultProps={
  value: [],
};

function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser
  }
}

const WrappedAddTableCell = Form.create()(AddTableCell);

export default connect(mapStateToProps)(WrappedAddTableCell)
